﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PhysicsControlModule.Daos;
using PhysicsControlModule.Models;
using PhysicsControlModule.Security;

namespace PhysicsControlModule.Controllers
{
    public class TutorController : Controller
    {
        //
        // GET: /Tutor/

        [Authorize(Roles = "TUTOR")]
        public ActionResult Cabinet()
        {
            TutorCabinetModel tutorCabinetModel =
                new TutorCabinetModel
                    {
                        PublishedLabworks = new List<PublishedLabworkModel>(),
                        AvailableLabworks = new List<AvailableLabworkModel>()
                    };

            int currUserId = MmShProvider.GetUser().Id;
            foreach (RelLabworkGroup loadPublishedLab in LabworkDao.LoadPublishedLabs(currUserId))
            {
                tutorCabinetModel.PublishedLabworks.Add(
                    new PublishedLabworkModel
                        {
                            LabworkId = loadPublishedLab.LabworkId,
                            LabworkTitle = LabworkDao.GetById(loadPublishedLab.LabworkId).Title,
                            GroupId = loadPublishedLab.GroupId,
                            GroupName = GroupDao.GetById(loadPublishedLab.GroupId).Name
                        });
            }

            foreach (Labwork labwork in LabworkDao.Load())
            {
                User owner = UserDao.GetById(labwork.OwnerId);
                tutorCabinetModel.AvailableLabworks.Add(
                    new AvailableLabworkModel
                        {
                            LabworkId = labwork.Id,
                            LabworkTitle = LabworkDao.GetById(labwork.Id).Title,
                            TutorFirstLastName = string.Format("{0} {1}", owner.FirstName, owner.LastName)
                        });
            }

            return View(tutorCabinetModel);
        }

        [Authorize(Roles = "TUTOR")]
        [HttpPost]
        public ActionResult Cabinet(int labworkId, string act)
        {
            // if (action == 1) Add to DB record about new published labwork
            // if (action == 0) Remove from DB record about published labwork
            return RedirectToAction("Cabinet");
        }

        [Authorize(Roles = "TUTOR")]
        public ActionResult Lab(int? labworkId)
        {
            Labwork labwork;
            if (labworkId.HasValue)
            {
                labwork = LabworkDao.GetById((int)labworkId);
            }
            else
                labwork = new Labwork
                            {
                                Id = 0,
                                Title = string.Empty,
                                Descr = string.Empty
                            };

            return View(labwork);
        }

        [Authorize(Roles = "TUTOR")]
        [HttpPost]
        public ActionResult Lab(int labworkId, Labwork labwork)
        {
            // Add or Edit Labwork record

            return RedirectToAction("Cabinet");
        }

        [Authorize(Roles = "TUTOR")]
        //[HttpPost]
        public ActionResult Statistics(int labworkId, int groupId)
        {
            int currUserId = MmShProvider.GetUser().Id;
            GroupStatisticsModel groupStatisticsModel =
                new GroupStatisticsModel
                    {
                        LabworkId = labworkId,
                        LabworkTitle = LabworkDao.GetById(labworkId).Title,
                        GroupId = groupId,
                        GroupName = GroupDao.GetById(groupId).Name,
                        StudentStatisticsModels = new List<StudentStatisticsModel>()
                    };
            foreach (User student in UserDao.LoadStudents(groupId))
                groupStatisticsModel.StudentStatisticsModels.Add(
                    new StudentStatisticsModel
                        {
                            StudentId = student.Id,
                            StudentFirstLastName = string.Format("{0} {1}", student.LastName, student.FirstName),
                            AdmRightAnswered = AdmQuestionDao.GetRightCount(labworkId, student.Id),
                            AdmQuestionsCount = AdmQuestionDao.GetCount(labworkId),
                            PeriphParamRightCount = PeriphParamDao.GetRightCount(labworkId, student.Id),
                            PeriphParamCount = PeriphParamDao.GetCount(labworkId, student.Id),
                            CtrlQuestionAnswered = CtrlQuestionDao.GetAnsweredCount(labworkId, student.Id),
                            CtrlQuestionCount = CtrlQuestionDao.GetCount(labworkId),
                            Mark = 0
                        });
            return View(groupStatisticsModel);
        }

        [Authorize(Roles = "TUTOR")]
        [HttpPost]
        public ActionResult Statistics(int labworkId, int groupId, GroupStatisticsModel groupStatisticsModel)
        {
            // TODO: Add new marks of student
            using (CmDbEntities db = new CmDbEntities())
            {
                if (groupStatisticsModel.StudentStatisticsModels != null)
                    foreach (StudentStatisticsModel model in groupStatisticsModel.StudentStatisticsModels)
                        if (model.Mark > 0)
                        {
                            RelLabworkUserConclusion relLabworkUserConclusion =
                                db.RelLabworkUserConclusion.FirstOrDefault(m => m.LabworkId == labworkId && m.UserId == model.StudentId);
                            if (relLabworkUserConclusion != null) relLabworkUserConclusion.Mark = model.Mark;
                            db.SaveChanges();
                        }
            }
            return RedirectToAction("Statistics", new {labworkId, groupId});
        }

        [Authorize(Roles = "TUTOR")]
        //[HttpPost]
        public ActionResult ClearStudentWork(int labworkId, int groupId, int studentId)
        {
            using (CmDbEntities db = new CmDbEntities())
            {
                // Clear admission questions
                List<RelLabworkUserAdmQuestionAnswer> relLabUsrAdmQuesAns =
                    db.RelLabworkUserAdmQuestionAnswer.Where(m => m.LabworkId == labworkId && m.UserId == studentId).ToList();
                foreach (RelLabworkUserAdmQuestionAnswer item in relLabUsrAdmQuesAns)
                {
                    db.DeleteObject(item);
                    db.SaveChanges();
                }

                // Clear periph params
                List<RelLabworkPeriphParamUser> relLabPerPrmUsrs =
                    db.RelLabworkPeriphParamUser.Where(m => m.LabworkId == labworkId && m.UserId == studentId).ToList();
                foreach (RelLabworkPeriphParamUser item in relLabPerPrmUsrs)
                {
                    db.DeleteObject(item);
                    db.SaveChanges();
                }

                // Clear conclusion
                RelLabworkUserConclusion relLabworkUserConclusion =
                    db.RelLabworkUserConclusion.FirstOrDefault(m => m.LabworkId == labworkId && m.UserId == studentId);

                // Clear control questions
                List<RelLabworkCtrlQuestionUser> relLabCtrlQuesUsrs =
                    db.RelLabworkCtrlQuestionUser.Where(m => m.LabworkId == labworkId && m.UserId == studentId).ToList();
                foreach (RelLabworkCtrlQuestionUser item in relLabCtrlQuesUsrs)
                {
                    db.DeleteObject(item);
                    db.SaveChanges();
                }
            }
            return RedirectToAction("Statistics", new { labworkId, groupId });
        }
    }
}
